package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.photography.MainActivity;
import com.example.photography.MainActivity2;
import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.bean.UserBean;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.util.CountDownTimerUtils;
import com.example.photography.util.Util;
import com.example.photography.view.LoadingDialog;
import com.mob.MobSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.smssdk.EventHandler;
import cn.smssdk.OnSendMessageHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Register_activity extends BaseActivity {


    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.auth_code)
    EditText authCode;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.password1)
    EditText password1;
    @BindView(R.id.password2)
    EditText password2;
    @BindView(R.id.register)
    Button register;
    private String phone_input;
    private CountDownTimerUtils countDownTimer;
    private String password;
    private String password_yanzheng;
    private String yanzheng_number;
    private String id;
    private String id_unique;
    private String head_url;
    private String name;
    private String hr_sign;


    @Override
    protected void initData() {
        // 通过代码注册你的AppKey和AppSecret
        MobSDK.init(Register_activity.this, "30fe366542c68", "507598498bab75a1b50f06ce857d376d");
        phone_input = phone.getText().toString();
        initLister();
    }

    private void initLister() {
        //监听手机号编辑框
        TextChange textChange = new TextChange();
        phone.addTextChangedListener(textChange);
        //发送验证码
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取验证码
                phone_input = phone.getText().toString();
                // 发送成功进入倒计时
                countDownTimer = new CountDownTimerUtils(send, 60000, 1000);
                countDownTimer.start();
                //获取验证码
                if (TextUtils.isEmpty(phone_input))
                    Util.showToast(Register_activity.this, "号码不能为空~");

                SMSSDK.getVerificationCode("86", phone_input, (OnSendMessageHandler) null);
            }
        });
        //注册按钮实现
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("url", AppNetConfig.register);
                //.trim()去除两边多余的空格
                password = password1.getText().toString().trim();
                password_yanzheng = password2.getText().toString().trim();
                yanzheng_number = authCode.getText().toString().trim();
                //提交验证码验证
                if (password.equals("") || password_yanzheng.equals("")) {
                    Util.showToast(getApplicationContext(), "密码不能为空");
                } else if (!password.equals(password_yanzheng)) {
                    Util.showToast(getApplicationContext(), "两次输入密码不一致");
                } else if (password.length() > 12) {
                    Util.showToast(getApplicationContext(), "密码过长啦,不能超过12位~");
                } else {
                    //开启等待动画
                    LoadingDialog.getInstance(Register_activity.this).show();

                    SMSSDK.submitVerificationCode("86", phone_input, yanzheng_number);
                }
            }
        });
        EventHandler eh = new EventHandler() {

            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    // 处理成功得到验证码的结果
                    // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                okhttp();
                            }
                        });

                    }
                } else {
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Util.showToast(Register_activity.this, "验证码错误~");
                        }
                    });
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调

    }

    private void okhttp() {
        password = password1.getText().toString().trim();

        OkHttpClient client = new OkHttpClient();

        //POST请求
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone_input)
                .add("password", password)
                .build();

        final Request request = new Request.Builder()
                .url(AppNetConfig.register)
                .post(formBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Util.showToast(getApplicationContext(), "后台君好像生病了~");
                        Log.e("tag", e.toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int result = Integer.parseInt(jsonObject.getString("status"));

                    if (result == 202) {//注册成功
                        JSONObject Object = jsonObject.getJSONObject("data");
                        JSONObject user = Object.getJSONObject("user");
                        JSONObject userIfo = Object.getJSONObject("user_info");
                        id = user.getString("id");
                        id_unique = user.getString("id_unique");

                        head_url = userIfo.getString("head_url");
                        name = userIfo.getString("name");
                        hr_sign = userIfo.getString("hr_sign");
                        mHandler.sendEmptyMessageDelayed(2, 0);//关闭等待动画，0延时

                    } else if (result == 401) {
                        JSONObject Object = jsonObject.getJSONObject("data");
                        JSONObject user = Object.getJSONObject("user");
                        JSONObject userIfo = Object.getJSONObject("user_info");
                        id = user.getString("id");
                        id_unique = user.getString("id_unique");

                        head_url = userIfo.getString("head_url");
                        name = userIfo.getString("name");
                        hr_sign = userIfo.getString("hr_sign");
                        mHandler.sendEmptyMessageDelayed(3, 0);//关闭等待动画，0延时

                    } else if (result == 404) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Util.showToast(getApplicationContext(), "请求错误");
                            }
                        });
                    } else if (result == 400) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Util.showToast(getApplicationContext(), "缺少字段");
                            }
                        });
                    }
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                } catch (JSONException e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Util.showToast(getApplicationContext(), "好像出错了~");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.register;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class TextChange implements TextWatcher {
        //获取账号密码编辑框

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            boolean Sign1 = phone.length() == 11;
            if (Sign1) {
                send.setEnabled(true);
            } else {
                send.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (LoadingDialog.getInstance(Register_activity.this) != null) {
                        LoadingDialog.getInstance(Register_activity.this).dismiss();
                    }
                    break;
                case 2:
                    Util.showToast(getApplicationContext(), "注册成功,请稍后...");
                    LoadingDialog.getInstance(Register_activity.this).dismiss();
                    action();
                case 3:
                    Util.showToast(getApplicationContext(), "该手机号已注册，直接登录,请稍后片刻...");
                    LoadingDialog.getInstance(Register_activity.this).dismiss();
                    action();
                    break;
            }
        }
    };

    private void action() {
        saveMessage();
        //获取全局UID
        Constant.UID = id_unique;
        //更新数据表
        UserBean.User user = new UserBean.User(id, id_unique, phone_input, password);
        UserBean.UserInfo userInfo = new UserBean.UserInfo(id_unique, head_url, name, hr_sign);
        Model.getInstance().getUerAccountDao().addAccount(user);

        //对模型层数据的处理
        //1. 初始化对象DBManger,DBHelper，建表
        Model.getInstance().loginSuccess(user);
        //2. 存数据
        Model.getInstance().getDbManger().getUserInfoDao().saveUserInfo(userInfo);
        goToActivity(MainActivity2.class, new Bundle());
        removeCurrentActivity();
    }

    /**
     * 保存用户登录过
     */
    private void saveMessage() {
        SharedPreferences preferences = getSharedPreferences("isLogin", MODE_PRIVATE);
        //实例化Editor对象
        SharedPreferences.Editor editor = preferences.edit();
        //存入数据
        //储存id
        editor.putString("UID", id_unique);
        //提交修改
        editor.apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除所有的未被执行的消息
        mHandler.removeCallbacksAndMessages(null);
    }
}
